package com.fastplatform.init;

import com.fastplatform.entity.Menu;
import com.fastplatform.entity.Role;
import com.fastplatform.entity.RoleMenu;
import com.fastplatform.entity.User;
import com.fastplatform.entity.UserRole;
import com.fastplatform.repository.MenuRepository;
import com.fastplatform.repository.RoleRepository;
import com.fastplatform.repository.RoleMenuRepository;
import com.fastplatform.repository.UserRepository;
import com.fastplatform.repository.UserRoleRepository;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import jakarta.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private MenuRepository menuRepository;

    @Autowired
    private RoleMenuRepository roleMenuRepository;

    @Override
    @Transactional
    public void run(String... args) throws Exception {

        // 判断用户表是否已有数据，若有则跳过初始化
        if (userRepository.count() > 0) {
            System.out.println("检测到已有用户数据，跳过初始化。");
            return;
        }

        System.out.println("开始初始化数据...");

        // 删除所有现有数据
        userRoleRepository.deleteAll();
        roleMenuRepository.deleteAll();
        menuRepository.deleteAll();
        roleRepository.deleteAll();
        userRepository.deleteAll();

        // 确保所有删除操作都已执行
        userRepository.flush();
        roleRepository.flush();
        userRoleRepository.flush();
        menuRepository.flush();
        roleMenuRepository.flush();
        
        // 创建角色
        Role adminRole = new Role();
        adminRole.setRoleName("管理员");
        adminRole.setRoleCode("ROLE_ADMIN");
        adminRole.setDescription("系统管理员");
        adminRole.setCreateTime(LocalDateTime.now());
        adminRole.setUpdateTime(LocalDateTime.now());
        roleRepository.saveAndFlush(adminRole);

        Role userRole = new Role();
        userRole.setRoleName("普通用户");
        userRole.setRoleCode("ROLE_USER");
        userRole.setDescription("普通用户");
        userRole.setCreateTime(LocalDateTime.now());
        userRole.setUpdateTime(LocalDateTime.now());
        roleRepository.saveAndFlush(userRole);

        // 创建角色
        // 创建默认管理员用户
        User adminUser = new User();
        adminUser.setUsername("admin");

        adminUser.setPassword(BCrypt.hashpw("123456", BCrypt.gensalt()));
        adminUser.setNickname("管理员");
        adminUser.setEmail("admin@example.com");
        adminUser.setPhone("13800138000");
        adminUser.setAvatar("");
        adminUser.setStatus(1);
        adminUser.setUserType(1); // 管理员
        adminUser.setCreateTime(LocalDateTime.now());
        adminUser.setUpdateTime(LocalDateTime.now());
        userRepository.saveAndFlush(adminUser);

        // 给管理员用户分配管理员角色
        UserRole adminUserRoleRelation = new UserRole();
        adminUserRoleRelation.setUserId(adminUser.getId());
        adminUserRoleRelation.setRoleId(adminRole.getId());
        adminUserRoleRelation.setCreateTime(LocalDateTime.now());
        adminUserRoleRelation.setUpdateTime(LocalDateTime.now());
        userRoleRepository.saveAndFlush(adminUserRoleRelation);

        // 创建多个测试用户
        String[] userNames = {"user1", "user2", "user3"};
        String[] nickNames = {"张三", "李四", "王五"};
        String[] emails = {"zhangsan@example.com", "lisi@example.com", "wangwu@example.com"};
        String[] phones = {"13800138001", "13800138002", "13800138003"};
        Integer[] statuses = {1, 1, 0}; // 前两个启用，第三个禁用
        
        for (int i = 0; i < userNames.length; i++) {
            User normalUser = new User();
            normalUser.setUsername(userNames[i]);
            normalUser.setPassword(BCrypt.hashpw("123456", BCrypt.gensalt()));
            normalUser.setNickname(nickNames[i]);
            normalUser.setEmail(emails[i]);
            normalUser.setPhone(phones[i]);
            normalUser.setAvatar("");
            normalUser.setStatus(statuses[i]);
            normalUser.setUserType(2); // 普通用户
            normalUser.setCreateTime(LocalDateTime.now());
            normalUser.setUpdateTime(LocalDateTime.now());
            userRepository.saveAndFlush(normalUser);

            // 给普通用户分配用户角色
            UserRole normalUserRoleRelation = new UserRole();
            normalUserRoleRelation.setUserId(normalUser.getId());
            normalUserRoleRelation.setRoleId(userRole.getId());
            normalUserRoleRelation.setCreateTime(LocalDateTime.now());
            normalUserRoleRelation.setUpdateTime(LocalDateTime.now());
            userRoleRepository.saveAndFlush(normalUserRoleRelation);
        }

        System.out.println("菜单数据初始化完成");

        // 初始化菜单数据
        List<Menu> menus = initMenus();

        // 给管理员角色分配所有菜单权限
        for (Menu menu : menus) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(adminRole.getId());
            roleMenu.setMenuId(menu.getId());
            roleMenuRepository.saveAndFlush(roleMenu);
        }

        // 给普通用户角色分配部分菜单权限（只读权限）
        for (Menu menu : menus) {
            // 普通用户只分配用户管理菜单权限
            if ("用户管理".equals(menu.getName())) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(userRole.getId());
                roleMenu.setMenuId(menu.getId());
                roleMenuRepository.saveAndFlush(roleMenu);
            }
        }

        System.out.println("数据初始化完成！");
    }

    private List<Menu> initMenus() {
        // 创建系统管理目录
        Menu systemMenu = new Menu();
        systemMenu.setName("系统管理");
        systemMenu.setPath("/system");
        systemMenu.setComponent("");
        systemMenu.setIcon("Setting");
        systemMenu.setMenuType(0); // 目录
        systemMenu.setSort(1);
        systemMenu.setParentId(0L);
        systemMenu.setStatus(1);
        systemMenu.setVisible(1);
        systemMenu.setCreateTime(LocalDateTime.now());
        systemMenu.setUpdateTime(LocalDateTime.now());
        systemMenu = menuRepository.saveAndFlush(systemMenu);

        // 创建用户管理菜单
        Menu userMenu = new Menu();
        userMenu.setName("用户管理");
        userMenu.setPath("/user-management");
        userMenu.setComponent("system/UserManagement");
        userMenu.setIcon("User");
        userMenu.setMenuType(1); // 菜单
        userMenu.setSort(1);
        userMenu.setParentId(systemMenu.getId());
        userMenu.setStatus(1);
        userMenu.setVisible(1);
        userMenu.setCreateTime(LocalDateTime.now());
        userMenu.setUpdateTime(LocalDateTime.now());
        userMenu = menuRepository.saveAndFlush(userMenu);

        // 创建菜单管理菜单
        Menu menuManagement = new Menu();
        menuManagement.setName("菜单管理");
        menuManagement.setPath("/menu-management");
        menuManagement.setComponent("system/MenuManagement");
        menuManagement.setIcon("Menu");
        menuManagement.setMenuType(1); // 菜单
        menuManagement.setSort(2);
        menuManagement.setParentId(systemMenu.getId());
        menuManagement.setStatus(1);
        menuManagement.setVisible(1);
        menuManagement.setCreateTime(LocalDateTime.now());
        menuManagement.setUpdateTime(LocalDateTime.now());
        menuRepository.saveAndFlush(menuManagement);

        // 创建角色管理菜单
        Menu roleManagement = new Menu();
        roleManagement.setName("角色管理");
        roleManagement.setPath("/role-management");
        roleManagement.setComponent("system/RoleManagement");
        roleManagement.setIcon("UserFilled");
        roleManagement.setMenuType(1); // 菜单
        roleManagement.setSort(3);
        roleManagement.setParentId(systemMenu.getId());
        roleManagement.setStatus(1);
        roleManagement.setVisible(1);
        roleManagement.setCreateTime(LocalDateTime.now());
        roleManagement.setUpdateTime(LocalDateTime.now());
        menuRepository.saveAndFlush(roleManagement);

        System.out.println("菜单数据初始化完成");
        
        return menuRepository.findAll();
    }
}